package com.bw.home.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.SizeUtils;
import com.bw.common.utils.LogUtils;

/**
 * @author:created by hahajing
 * 时间：2024/4/28 0028
 * 企鹅号:444511958
 * 描述:
 */
public class FlowLayout extends ViewGroup {
    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
    }

    private int currentWidth=0;
    private int currentHeight=0;

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        currentWidth=getMeasuredWidth();
        currentHeight=getMeasuredHeight();
    }

    private int lastestX=0;
    private int lastestY=0;

    private boolean layouted = false;
    private int defaultMargin = SizeUtils.dp2px(10.0f);
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (layouted){
            return;
        }

        int childCount = getChildCount();
        for (int i=0;i<childCount;i++){
            View subView = getChildAt(i);
            LogUtils.INSTANCE.d("FlowLayout",String.format("l = %d t = %d r = %d b = %d",lastestX,lastestY,lastestX+subView.getMeasuredWidth(),subView.getMeasuredHeight()));
            if (lastestX+subView.getMeasuredWidth()+(defaultMargin*2)>currentWidth){
                lastestY+=subView.getMeasuredHeight()+defaultMargin;
                lastestX=0;
            }
            subView.layout(defaultMargin+lastestX,defaultMargin+lastestY,defaultMargin+lastestX+subView.getMeasuredWidth(),defaultMargin+lastestY+subView.getMeasuredHeight());

            lastestX+=subView.getMeasuredWidth()+defaultMargin;

            LogUtils.INSTANCE.d("FlowLayout",String.format("lastestX = %d",lastestX));

        }
        layouted=true;
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

    }
}
